<?php

namespace adibilis\adminBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use adibilis\adminBundle\Entity\PassOrder;
use adibilis\adminBundle\Entity\OrderStatus;
use adibilis\adminBundle\Form\PassOrderType;
use adibilis\adminBundle\Form\PassOrderEditType;
use JMS\SecurityExtraBundle\Annotation\Secure;

/**
 * PassOrder controller.
 *
 * @Route("/passorder")
 */
class PassOrderController extends Controller
{


    public function descAction()
    {
       return $this->render('adibilisadminBundle:PassOrder:desc.html.twig');
    }



    /**
     * Lists all PassOrder entities.
     *
     * @Route("/", name="passorder")
     * @Template()
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();

        $entities = $em->getRepository('adibilisadminBundle:PassOrder')->findAll();

        return array(
            'entities' => $entities,
        );
    }

    /**
     * Finds and displays a PassOrder entity.
     *
     * @Route("/{id}/show", name="passorder_show")
     * @Template()
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:PassOrder')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PassOrder entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Displays a form to create a new PassOrder entity.
     *
     * @Route("/new", name="passorder_new")
     * @Template()
     * @Secure(roles="ROLE_USER")
     */
    public function newAction()
    {
        $entity = new PassOrder();
        $form   = $this->createForm(new PassOrderType(), $entity);


        if (!$this->get('security.context')->isGranted('ROLE_USER') || !$this->get('security.context')->isGranted('ROLE_USER')) {

            $this->get('session')->getFlashBag()->add('info', 'Veuillez vous connecter afin de pouvoir commander le pass');
            return $this->redirect($this->generateUrl('fos_user_security_login'));

        }


        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Creates a new PassOrder entity.
     *
     * @Route("/create", name="passorder_create")
     * @Method("POST")
     * @Template("adibilisadminBundle:PassOrder:new.html.twig")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function createAction(Request $request)
    {
        $entity  = new PassOrder();


        //On assigne l'utilisateur connecté !
        $entity->setUser($this->get('security.context')->getToken()->getUser());



        $em2 = $this->getDoctrine()->getManager();

        $status = $em2->getRepository('adibilisadminBundle:OrderStatus')->find(1);


        $entity->setStatus($status);
        

/*
        // utilisateur actuel
        $currentUser = $this->get('security.context')->getToken()->getUser();

        // on va chercher si il existe déjà une commande avec ce nom d'utilisateur
        $userOrder = $em->getRepository('adibilisadminBundle:PassOrder')->findByUser($currentUser);
*/


        $mailadress = $this->get('security.context')->getToken()->getUser()->getEmail();

        $form = $this->createForm(new PassOrderType(), $entity);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();




            // Récupération du service d'envoi de mail
                $mailer = $this->get('mailer');
             
                // Création de l'e-mail : le service mailer utilise SwiftMailer, donc nous créons une instance de Swift_Message
                // Message pour le client
                $message = \Swift_Message::newInstance()
                  ->setSubject('Votre commande de pass')
                  ->setFrom('test@adibilis.ch')
                  ->setTo($mailadress)
                  ->setBody('Bonjour, merci pour votre commande.

                    Un deuxième mail vous sera bientôt envoyé avec plus de détails.'


                    );
             
                // Retour au service mailer, nous utilisons sa méthode « send() » pour envoyer notre $message

                $mailer->send($message);

                // Message pour l'admin
                $message = \Swift_Message::newInstance()
                  ->setSubject('Nouvelle commande de pass')
                  ->setFrom('test@adibilis.ch')
                  ->setTo('kummergab@gmail.com')
                  ->setBody('Reçu une nouvelle commande'

                    );
             
                // Retour au service mailer, nous utilisons sa méthode « send() » pour envoyer notre $message
                $mailer->send($message);
             
       


        // On définit un message flash
        $this->get('session')->getFlashBag()->add('info', 'Commande envoyée');

            return $this->redirect($this->generateUrl('passorder_new'));
        }

        return array(
            'entity' => $entity,
            'form'   => $form->createView(),
        );
    }

    /**
     * Displays a form to edit an existing PassOrder entity.
     *
     * @Route("/{id}/edit", name="passorder_edit")
     * @Template()
     * @Secure(roles="ROLE_ADMIN")
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:PassOrder')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PassOrder entity.');
        }

        $editForm = $this->createForm(new PassOrderEditType(), $entity);
        $deleteForm = $this->createDeleteForm($id);

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Edits an existing PassOrder entity.
     *
     * @Route("/{id}/update", name="passorder_update")
     * @Method("POST")
     * @Template("adibilisadminBundle:PassOrder:edit.html.twig")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('adibilisadminBundle:PassOrder')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find PassOrder entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createForm(new PassOrderEditType(), $entity);
        $editForm->bind($request);

        if ($editForm->isValid()) {
            $em->persist($entity);
            $em->flush();




            $this->get('session')->getFlashBag()->add('info', 'Commande bien modifiée');
            return $this->redirect($this->generateUrl('passorder_edit', array('id' => $id)));
        }

        return array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        );
    }

    /**
     * Deletes a PassOrder entity.
     *
     * @Route("/{id}/delete", name="passorder_delete")
     * @Method("POST")
     * @Secure(roles="ROLE_ADMIN")
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('adibilisadminBundle:PassOrder')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find PassOrder entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('passorder_list'));
    }

    private function createDeleteForm($id)
    {
        return $this->createFormBuilder(array('id' => $id))
            ->add('id', 'hidden')
            ->getForm()
        ;
    }
}
